const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'

function MyPromise(fn) {
    const that = this
    that.state = PENDING
    that.value = null // 存放resolve()内部的参数
    that.resolvedCallbacks = [] // then里面的回调函数1
    that.rejectedCallbacks = [] // then里面的回调函数2

    function resolve(value) {
        if(that.state === PENDING)
        {
            that.state = RESOLVED
            that.value = value
            that.resolvedCallbacks.map(cb => cb(that.value))
        }
    }

    function reject(value) {
        if(that.state === REJECTED) {
          that.state = REJECTED
          that.value = value
          that.rejectedCallbacks.map(cb => cb(that.value))
        }
    }


    try {
        fn(resolve, reject)
    } catch (error) {
        reject(error)
    }
}


MyPromise.prototype.then = function(onFulfied, onRejected) {
    // this.value
    const that = this
    onFulfied = typeof onFulfied === 'function' ? onFulfied : v => v
    onRejected = typeof onRejected === 'function' ? onRejected : r => {
        throw r
    }

    if(that.state === PENDING) {
        that.resolvedCallbacks.push(onFulfied)
        that.rejectedCallbacks.push(onRejected)
    }

    if(that.state === RESOLVED) {
        onFulfied(that.value)
    }
    if(that.state === REJECTED) {
        onRejected(taht.value)
    }
}

const p = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve('ok')
    })
}, 1000).then(
    res => {
        console.log(res);
    }
)